package com.yzkj.siot.aspect;

import com.yzkj.siot.annotation.Permission;
import com.yzkj.siot.context.CurUserCtx;
import com.yzkj.siot.exp.BizExp;
import com.yzkj.siot.token.TokenHelper;
import com.yzkj.siot.uesr.dto.CurrentUser;
import com.yzkj.siot.util.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(com.yzkj.siot.annotation.Permission)")
    public void permission() {
    }

    @Before("permission()")
    public void doBefore(JoinPoint joinPoint) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        // 获取请求头token存放的token
        String token = request.getHeader("token");

        if (token == null) {
            throw new BizExp("Token缺失！");
        }

        // 获取注解中的参数值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Permission permissionAnnotation = method.getAnnotation(Permission.class);

        int permissionType = permissionAnnotation.type().getTypeCode();
        CurrentUser curUser = TokenHelper.getCurrentUser(token);
        Integer userType = curUser.getUserType();

        if (userType != permissionType && permissionType != 0) {
            throw new BizExp("权限不足");
        }

        CurUserCtx.set(curUser);
    }
}